<template>
  <div class="messages-container">
    <div class="messages-header">
      <div class="header-left">
        <h2>消息中心</h2>
        <span class="message-count">{{ messages.length }} 条消息</span>
      </div>
      
      <div class="header-actions">
        <el-button
          v-if="unreadCount > 0"
          type="primary"
          size="small"
          @click="handleMarkAllRead"
        >
          全部标记为已读
        </el-button>
        
        <el-dropdown @command="handleDropdownCommand">
          <el-button size="small">
            更多操作
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="refresh">刷新消息</el-dropdown-item>
              <el-dropdown-item command="clear" divided>清空所有消息</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <div class="messages-content">
      <div v-if="messages.length === 0" class="empty-state">
        <el-empty description="暂无消息" />
      </div>
      
      <div v-else class="message-list">
        <div
          v-for="message in sortedMessages"
          :key="message.id"
          class="message-item"
          :class="{ unread: !message.isRead }"
          @click="handleMessageClick(message)"
        >
          <div class="message-indicator">
            <div v-if="!message.isRead" class="unread-dot"></div>
          </div>
          
          <div class="message-content">
            <div class="message-header">
              <h4 class="message-title">{{ message.title }}</h4>
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            </div>
            
            <div class="message-meta">
              <span class="message-source">{{ message.source }}</span>
            </div>
            
            <p class="message-summary">{{ message.summary }}</p>
          </div>
          
          <div class="message-actions">
            <el-button
              type="text"
              size="small"
              @click.stop="handleToggleRead(message)"
            >
              {{ message.isRead ? '标记未读' : '标记已读' }}
            </el-button>
            
            <el-button
              type="text"
              size="small"
              @click.stop="handleDeleteMessage(message)"
              class="delete-button"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useMessageStore } from '../stores/message'
import { formatDistanceToNow } from '../utils/date'

const router = useRouter()
const messageStore = useMessageStore()

const messages = computed(() => messageStore.messages)
const sortedMessages = computed(() => messageStore.sortedMessages)
const unreadCount = computed(() => messageStore.unreadCount)

const handleMessageClick = (message) => {
  router.push(`/main/message/${message.id}`)
}

const handleToggleRead = (message) => {
  if (message.isRead) {
    // 标记为未读（需要修改消息状态）
    message.isRead = false
    messageStore.saveToLocal?.()
  } else {
    messageStore.markAsRead(message.id)
  }
}

const handleDeleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除消息"${message.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    messageStore.deleteMessage(message.id)
    ElMessage.success('消息已删除')
  } catch (error) {
    // 用户取消
  }
}

const handleMarkAllRead = () => {
  messageStore.markAllAsRead()
  ElMessage.success('所有消息已标记为已读')
}

const handleDropdownCommand = async (command) => {
  switch (command) {
    case 'refresh':
      ElMessage.success('消息已刷新')
      break
      
    case 'clear':
      try {
        await ElMessageBox.confirm(
          '确定要清空所有消息吗？此操作不可恢复。',
          '确认清空',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        messageStore.clearAllMessages()
        ElMessage.success('所有消息已清空')
      } catch (error) {
        // 用户取消
      }
      break
  }
}

const formatTime = (timestamp) => {
  return formatDistanceToNow(new Date(timestamp))
}
</script>

<style lang="scss" scoped>
.messages-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid $border-color;
  background: white;
  
  .header-left {
    display: flex;
    align-items: baseline;
    gap: 12px;
    
    h2 {
      margin: 0;
      color: $text-color-primary;
      font-size: 20px;
      font-weight: 600;
    }
    
    .message-count {
      color: $text-color-secondary;
      font-size: 14px;
    }
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.messages-content {
  flex: 1;
  overflow: hidden;
}

.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-list {
  height: 100%;
  overflow-y: auto;
  padding: 0;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 16px 24px;
  border-bottom: 1px solid $border-color-light;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background: $hover-bg;
  }
  
  &.unread {
    background: rgba($primary-color, 0.02);
    border-left: 3px solid $primary-color;
  }
}

.message-indicator {
  width: 20px;
  display: flex;
  justify-content: center;
  padding-top: 4px;
  
  .unread-dot {
    width: 8px;
    height: 8px;
    background: $primary-color;
    border-radius: 50%;
  }
}

.message-content {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 4px;
  
  .message-title {
    margin: 0;
    font-size: 15px;
    font-weight: 500;
    color: $text-color-primary;
    line-height: 1.4;
  }
  
  .message-time {
    color: $text-color-secondary;
    font-size: 12px;
    white-space: nowrap;
    margin-left: 12px;
  }
}

.message-meta {
  margin-bottom: 8px;
  
  .message-source {
    color: $text-color-secondary;
    font-size: 12px;
    background: $bg-color;
    padding: 2px 6px;
    border-radius: 3px;
  }
}

.message-summary {
  margin: 0;
  color: $text-color-regular;
  font-size: 13px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-left: 12px;
  opacity: 0;
  transition: opacity 0.2s;
  
  .message-item:hover & {
    opacity: 1;
  }
  
  .delete-button {
    color: $danger-color;
    
    &:hover {
      background: rgba($danger-color, 0.1);
    }
  }
}
</style>